package com.ntschy.framework.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ntschy.common.annotation.OperationDataScope;
import com.ntschy.common.constant.HttpStatus;
import com.ntschy.common.core.AjaxResult;
import com.ntschy.common.core.entity.dataobject.SysMenu;
import com.ntschy.common.core.entity.enums.SysDataScopeEnum;
import com.ntschy.common.filter.RepeatedlyRequestWrapper;
import com.ntschy.common.utils.SecurityUtils;
import com.ntschy.common.utils.ServletUtils;
import com.ntschy.common.utils.http.HttpHelper;
import com.ntschy.common.utils.spring.SpringUtils;
import com.ntschy.sys.service.ISysRoleService;
import com.ntschy.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 操作数据权限拦截起
 * @author ezreal_geng
 */
@Component
public class OperationDataScopeInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        OperationDataScope operationDataScope = method.getAnnotation(OperationDataScope.class);
        if (ObjectUtil.isNotNull(operationDataScope)) {
            // TODO 这写你拦截需要干的事儿，比如取缓存，SESSION，权限判断等
            String roleKey = SecurityUtils.getUser().getRole().getRoleKey();
            String userId = SecurityUtils.getUser().getId();
            String companyId = SecurityUtils.getUser().getCompanyId();
            String deptId = SecurityUtils.getUser().getDeptId();
            // 当前请求uri
            String uri = request.getRequestURI();

            SysMenu currentBtn = null;
            List<SysMenu> menuBtnList = roleService.listMenuBtnByRole(roleKey);
            for (int i = 0; i < menuBtnList.size(); i++) {
                SysMenu menuBtn = menuBtnList.get(i);
                if(uri.equals(menuBtn.getHttpUrl())) {
                    currentBtn = menuBtn;
                    break;
                }
            }

            if(ObjectUtil.isNotNull(currentBtn)) {
                // 当前操作数据主键名
                String pk = operationDataScope.filedPk();
                // 当前操作数据权限字段
                String filedName = operationDataScope.dataScopeFiledName();
                // 当前操作数据主键值
                String pkValue = "";


                if (request instanceof RepeatedlyRequestWrapper) {
                    RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
                    String httpParams = HttpHelper.getBodyString(repeatedlyRequest);
                    Map map = (Map)JSONObject.parse(httpParams);
                    if(ObjectUtil.isNull(map)) {
                        notAllowResponse(response, "数据操作权限入参异常");
                        return false;
                    }
                    pkValue = (String)map.get(operationDataScope.propPk());
                } else {
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    if(CollectionUtil.isNotEmpty(parameterMap) && ObjectUtil.isNotNull(parameterMap.get(operationDataScope.propPk()))) {
                        pkValue = parameterMap.get(operationDataScope.propPk())[0];
                    } else {
                        notAllowResponse(response, "数据操作权限入参异常");
                        return false;
                    }

                }

                // userId集合
                List<String> userIdList = new ArrayList<>();
                if(currentBtn.getDataScope() == SysDataScopeEnum.COMPANY) {
                    // 公司
                    userIdList = userService.listUserIdByCompany(companyId);
                } else if(currentBtn.getDataScope() == SysDataScopeEnum.DEPT) {
                    // 部门
                    userIdList = userService.listUserIdByDept(deptId);
                } else if(currentBtn.getDataScope() == SysDataScopeEnum.SELF) {
                    // 个人
                    userIdList.add(userId);
                } else {
                    return true;
                }

                BaseMapper mapper = (BaseMapper)SpringUtils.getBean(operationDataScope.mapperClass());
                Object rs = mapper.selectOne(new QueryWrapper<>().eq(pk, pkValue).in(filedName, userIdList));

                if(ObjectUtil.isNull(rs)) {
                    notAllowResponse(response, "当前无此数据操作权限");
                    return false;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public static void notAllowResponse(HttpServletResponse response, String msg) {
        AjaxResult<String> ajaxResult = AjaxResult.error(HttpStatus.FORBIDDEN, msg);
        ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
    }

}
